<?php
/**
 * Description of Rest
 *
 * @author Lille
 */
class Koncept_Rest_Request_Http extends Zend_Controller_Request_Http {

    /**
     *
     * @var bool Enables method overriding
     */
    public $useMethodHack = false;

    /**
     *
     * @var mixed Allowed methods. Either an array of methods or the string 'ALL'
     */
    public $allowedMethods = array('PUT', 'GET', 'POST', 'OPTIONS', 'HEAD', 'TRACE');

    /**
     *
     * @var string Method to use if requested method is not allowed
     */
    public $fallbackMethod = 'GET';

    public function getMethod() {
        if($this->useMethodHack) {
            return $this->_getComputedMethod();
        } else {
            return $this->_getRealMethod();
        }
    }

    /**
     *
     * @return string The real HTTP request method
     */
    protected function _getRealMethod() {
        return parent::getMethod();
    }

    /**
     *
     * @return string Real method, overriden method or the fallback method
     */
    protected function _getComputedMethod() {
        $realRequestMethod = strtolower($this->getRealMethod());
        if ($realRequestMethod == 'post') {
            // Store the requested method into $requestedMethod
            if ($requestedMethod = $this->getParam('_method')) {
            } elseif ($requestedMethod = $request->getHeader('X-HTTP-Method-Override')) {
            } else {
                return $requestMethod;
            }
            // Now check if the requested method is allowed
            if($this->_isMethodAllowed()) {
                return strtoupper($requestedMethod);
            }
        }

        // If no method override was set, return the real method, if allowed
        // else return the fallback method
        if($this->_isMethodAllowed($realRequestMethod)) {
            return $realRequestMethod;
        } else {
            return $this->fallbackMethod;
        }

    }
/**
 *
 * @param string check if method is allowed
 * @return bool
 */
    protected function _isMethodAllowed($method) {
        return ((is_string($this->allowedMethods) && $this->allowedMethods == 'ALL')
                || (is_array($this->allowedMethods)
                    && array_search(strtoupper($method), $this->allowedMethods)));
    }

    public function getQuerystring()
    {
        return $_SERVER['QUERY_STRING'];
    }
}